package demo.liu.two.controller;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @ClassName TestController
 * @Description TODO
 * @Author Liujt
 * @Date 2019/11/25 15:21
 **/
@Slf4j
@RestController
@RequestMapping("test")
public class TestController {

    @HystrixCommand(fallbackMethod = "fail2")
    @GetMapping("feign")
    public Map testFeign() {
        return new HashMap() {{
            this.put("msg", "I am feign");
        }};
    }

    @GetMapping("fail2")
    public Map fail2() {
        return new HashMap() {{
            this.put("msg", "失败熔断");
        }};
    }

    @GetMapping("testDynamicDataSource/{state}")
    public Object testDynamicRoutingDataSource(@PathVariable("state") Integer state) {

        return null;
    }

    private DataSource convertDataSourceEntity2DataSource(String url, String userName, String pwd) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("");
        dataSource.setUsername("");
        dataSource.setPassword("");
        dataSource.setInitialSize(0);
        dataSource.setMaxActive(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxWait(0);
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setValidationQuery("");
        dataSource.setTimeBetweenEvictionRunsMillis(1000);
        dataSource.setMinEvictableIdleTimeMillis(1000);
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(80);
        List<Filter> filters = new ArrayList<>(10);
        /*filters.addAll(proxyFilters);
        Filter filter = (Filter) AppUtil.getBean("multiTenantPlugin");*/
        //注入拦截器
        /*if (filter != null) {
            if (((MySqlInterceptor) filter).isEnableFilter()) {
                logger.debug("multiTenantPlugin Filter added");
                filters.add(filter);
            }
        }*/
        /*Properties properties = (Properties) connectionProperties.clone();
        String decryptEnable = properties.getProperty("config.decrypt");
        if (StringUtils.isNotEmpty(decryptEnable) && Boolean.valueOf(decryptEnable)) {
            properties.setProperty("config.decrypt.key", dataSourceEntity.getPwdKey());
        }*/
        dataSource.setProxyFilters(filters);
        //dataSource.setConnectProperties(properties);
        dataSource.setTimeBetweenConnectErrorMillis(60000);
        return dataSource;
    }

    public static void testSuccess(int i, RestTemplate restTemplate) {
        String urlSuccess = "http://127.0.0.1:9009/demoOne/testWebsocket/test?status=1";
        Long sunDate = System.currentTimeMillis();
        String res = restTemplate.getForObject(urlSuccess, String.class);
        log.info("次数：{}，成功结束时间：{},成功结果：{}", i, System.currentTimeMillis() - sunDate, res);
    }

    public static void testFail(int i, RestTemplate restTemplate) {
        String urlError = "http://127.0.0.1:9009/demoOne/testWebsocket/test?status=0";
        long currentTime = System.currentTimeMillis();
        String res = restTemplate.getForObject(urlError, String.class);
        log.info("次数：{}，失败结束时间：{}，结果：{}", i, System.currentTimeMillis() - currentTime, res);
    }

    public static void test(int i, RestTemplate restTemplate) {
        String urlError = "http://127.0.0.1:9009/demoOne/testWebsocket/test?status=0";
        long currentTime = System.currentTimeMillis();
        String res = restTemplate.getForObject(urlError, String.class);
        log.info("次数：{}，失败结束时间：{}，结果：{}", i, System.currentTimeMillis() - currentTime, res);

        String urlSuccess = "http://127.0.0.1:9009/demoOne/testWebsocket/test?status=1";
        Long sunDate = System.currentTimeMillis();
        res = restTemplate.getForObject(urlSuccess, String.class);
        log.info("次数：{}，成功结束时间：{},成功结果：{}", i, (System.currentTimeMillis() - sunDate) / 1000, res);
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            log.error("--------");
        }
    }


    public static long b = 0;
    public static long a = 0;

    /*public static void main(String[] args) {
        while (true) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(TestController.class);
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                    return proxy.invokeSuper(obj, args);
                }
            });
            enhancer.create();
        }
    }*/

    public static void callTest(long b) {
        while (true) {
            System.out.println(b);
            b++;
            callTest(b);
        }
    }

    public static void main(String[] args) {

    }
}
